module ecs{
    /**
     * 设计为其通用的简单事件发射器
     */
    export class Emitter {
        private _messageTable: {[key: string]: Array<Function>};

        constructor(){
            this._messageTable = {};
        }

        public AddObserver(eventType: string, handler: Function){
            let list: Array<Function> = null;
            if (!this._messageTable[eventType]){
                list = [];
                this._messageTable[eventType] = list;
            }

            if (list.indexOf(handler) != -1){
                throw new Error("您尝试两次添加相同的观察者");
            }

            list.push(handler);
        }

        public RemoveObserver(eventType: string, handler: Function){
            var index = this._messageTable[eventType].indexOf(handler);
            if (index != -1){
                this._messageTable[eventType].splice(index, 1);
            }
        }

        public Emit(eventType: string){
            let list: Array<Function> = null;
            if (this._messageTable[eventType]){
                for (let i = list.length - 1; i >= 0; i--) {    
                    list[i]();      
                }
            }
        }
    }
}